package com.clm.service.impl;

import com.aliyun.oss.ServiceException;
import com.clm.constant.MessageConstant;
import com.clm.constant.StatusConstant;
import com.clm.dto.SetmealDTO;
import com.clm.dto.SetmealPageQueryDTO;
import com.clm.entity.Dish;
import com.clm.entity.Setmeal;
import com.clm.entity.SetmealDish;
import com.clm.exception.DeletionNotAllowedException;
import com.clm.exception.SetmealEnableFailedException;
import com.clm.mapper.DishMapper;
import com.clm.mapper.SetmealDishMapper;
import com.clm.mapper.SetmealMapper;
import com.clm.result.PageResult;
import com.clm.service.SetMealService;
import com.clm.vo.DishItemVO;
import com.clm.vo.SetmealVO;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 * @Author dinghuapeng
 * @Date 2023/11/2 14:21
 * @PackageName:com.clm.service.impl
 * @ClassName: SetMealServiceImpl
 * @Description: TODO
 * @Version 1.0
 */
@Slf4j
@Service
public class SetMealServiceImpl implements SetMealService {


    @Autowired
    private SetmealMapper setmealMapper;

    @Autowired
    private SetmealDishMapper setmealDishMapper;
    @Autowired
    private DishMapper dishMapper;
    @Override
    public void save(SetmealDTO setmealDTO) {
        log.info("新增套餐：{}",setmealDTO);
        Setmeal setmeal=new Setmeal();
        BeanUtils.copyProperties(setmealDTO,setmeal);

        //向setmeal表中插入数据
        setmealMapper.insert(setmeal);

        Long id = setmeal.getId();//获取生成的主键值
        //向setmeal_dish表中插入数据（菜品）
        //从DTO中获取套餐菜品列表
        List<SetmealDish> setmealDishes = setmealDTO.getSetmealDishes();
        if(setmealDishes != null && setmealDishes.size()>0){
            setmealDishes.forEach(setmealDish ->
                                        setmealDish.setSetmealId(id));
            setmealDishMapper.insertSetmealDish(setmealDishes);
        }
    }

    /**
     * 套餐分页查询
     * @param setmealPageQueryDTO
     * @return
     */
    @Override
    public PageResult setmealPageQuery(SetmealPageQueryDTO setmealPageQueryDTO) {
        PageHelper.startPage(setmealPageQueryDTO.getPage(),setmealPageQueryDTO.getPageSize());
        Page<SetmealVO> page=setmealMapper.pageQuery(setmealPageQueryDTO);
        return new PageResult(page.getTotal(),page.getResult());
    }

    /**
     * 批量删除套餐
     * @param ids
     */
    @Override
    @Transactional
    public void delete(List<Long> ids) {
        //判断当前套餐是否能够删除--起售中的套餐不能删除
        for (Long id:ids){
            //取出当前套餐的状态
            //1.通过id查询数据
            Setmeal setmeal=setmealMapper.getByid(id);
            if(setmeal.getStatus()== StatusConstant.ENABLE){
                throw new DeletionNotAllowedException(MessageConstant.SETMEAL_ON_SALE);
            }
        }

        //判断是否选中套餐
        if(ids.size()<1){
            throw new DeletionNotAllowedException(MessageConstant.SETMEAL_NOT_FOUND);
        }

        //删除表中的数据
        for (Long id:ids){
            //删除套餐表中的数据
            setmealMapper.delete(id);

            //删除套餐表相关菜品中的数据
            setmealDishMapper.deleteBySetmealId(id);
        }
    }

    /**
     * 修改套餐
     * @param setmealDTO
     */
    @Override
    public void update(SetmealDTO setmealDTO) {
        Setmeal setmeal = new Setmeal();

        BeanUtils.copyProperties(setmealDTO,setmeal);
        //修改setmeal表
        setmealMapper.update(setmeal);

        //获取setmeat_id
        Long setmealId=setmealDTO.getId();

        //删除setmeal_dish表中与setmeat_id相关联的部分
        setmealDishMapper.deleteBySetmealId(setmealId);

        //重新插入数据
        //向setmeal_dish表中插入数据（菜品）
        //从DTO中获取套餐菜品列表
        List<SetmealDish> setmealDishes = setmealDTO.getSetmealDishes();
        if(setmealDishes != null && setmealDishes.size()>0){
            setmealDishes.forEach(setmealDish ->
                    setmealDish.setSetmealId(setmealId));
            setmealDishMapper.insertSetmealDish(setmealDishes);
        }

    }


    /**
     * 根据id查询套餐里的菜品
     *
     * @param id
     * @return
     */
    @Override
    public SetmealVO getByIdWithDish(Long id) {
        SetmealVO setmealVO=new SetmealVO();
        Setmeal setmeal=setmealMapper.getByid(id);
        List<SetmealDish> setmealDishes=new ArrayList<>();
        setmealDishes = setmealDishMapper.getBySetmealId(id);
        BeanUtils.copyProperties(setmeal,setmealVO);
        setmealVO.setSetmealDishes(setmealDishes);
        log.info("菜品数据：{}",setmealVO);
        return setmealVO;
    }

    /**
     * 起售或停售套餐
     */
    @Override
    public void startOrStop(Integer status, Long id) {
        //起售套餐时，判断套餐内是否有停售菜品，有停售菜品提示"套餐内包含未启售菜品，无法启售"
        if(status == StatusConstant.ENABLE){
            //select a.* from dish a left join setmeal_dish b on a.id = b.dish_id where b.setmeal_id = ?
            List<Dish> dishList = dishMapper.getBySetmealId(id);
            if(dishList != null && dishList.size() > 0){//循环
                dishList.forEach(dish -> {
                    if(StatusConstant.DISABLE == dish.getStatus()){
                        throw new SetmealEnableFailedException(MessageConstant.SETMEAL_ENABLE_FAILED);
                    }
                });
            }
        }

        Setmeal setmeal=new Setmeal();
        setmeal.setId(id);
        setmeal.setStatus(status);
        setmealMapper.update(setmeal);
    }

    /**
     * 条件查询
     * @param setmeal
     * @return
     */
    public List<Setmeal> list(Setmeal setmeal) {
        List<Setmeal> list = setmealMapper.list(setmeal);
        return list;
    }

    /**
     * 根据id查询菜品选项
     * @param id
     * @return
     */
    public List<DishItemVO> getDishItemById(Long id) {
        return setmealMapper.getDishItemBySetmealId(id);
    }
}
